﻿using System;
using System.Xml;

namespace XamlLocalizer.Parsing
{
    public class LocXReplacement : IReplacementStrategy
    {
        private string locTextExtPrefix;

        public string Id
        {
            get { return "LocX"; }
        }

        public string Name
        {
            get { return "LocX Extension"; }
        }

        public override string ToString()
        {
            return Name;
        }

        public bool ExtractRootElementAttributesIntoElements { get {return false;} }

        private static XamlParseInfo XamlParseInfo
        {
            get { return XamlExtractor.XamlParseInfo; }
        }

        private static string LocTextElementName
        {
            get { return XamlParseInfo.ReplaceSettings.LocTextElem; }
        }

        private void EnsureInit()
        {
            if (locTextExtPrefix != null) return;

            locTextExtPrefix = String.IsNullOrEmpty(XamlParseInfo.ReplaceSettings.LocExtPrefix)
                          ? "{" + LocTextElementName + " "
                          : "{" + XamlParseInfo.ReplaceSettings.LocExtPrefix + ":" + LocTextElementName + " ";

        }

        private static string GetFullKey(ResourceKeyDesc keyDesc)
        {
            return String.Format("{0}:{1}:{2}", keyDesc.Assembly, keyDesc.ResourceFile, keyDesc.ItemKey);
        }

        public string GetAttributeReplacementValue(ResourceKeyDesc keyDesc)
        {
            EnsureInit();
            string newValue = String.Format("{0}{1}}}", locTextExtPrefix, GetFullKey(keyDesc));
            return newValue;
        }

        public XmlElement CreateReplacementElement(XmlDocument ownerDoc, ResourceKeyDesc keyDesc)
        {
            EnsureInit();
            XmlElement newElem = ownerDoc.CreateElement(LocTextElementName, XamlParseInfo.ReplaceSettings.LocExtNamespace);
            newElem.SetAttribute(XamlParseInfo.ReplaceSettings.ResIdAttribute, GetFullKey(keyDesc));
            return newElem;
        }

        public void PrepareReplacement(XamlExtractor xamlExtractor, string resourcesNamespace, string resourceClass)
        {
            if (XamlParseInfo.ReplaceSettings.AddAssemblyResourcesNamespace)
            {
                xamlExtractor.AddNamespace("resources", "clr-namespace:" + resourcesNamespace);
            }

            if (!String.IsNullOrEmpty(XamlParseInfo.ReplaceSettings.LocExtPrefix))
            {
                xamlExtractor.AddNamespace(XamlParseInfo.ReplaceSettings.LocExtPrefix, XamlParseInfo.ReplaceSettings.LocExtNamespace);
            }
        }
    }
}
